﻿using System;
using System.Net;
using EnvDTE;
using Microsoft.SqlServer.Management.Smo.RegSvrEnum;
using Microsoft.SqlServer.Management.UI.VSIntegration;
using Microsoft.SqlServer.Management.UI.VSIntegration.Editors;

namespace CnSharp.SSMS.AddIn.Util
{
    public class DocumentHelper
    {
        public static string GetActiveDocumentSelectionText()
        {
            if (ServiceCache.ExtensibilityModel.ActiveDocument == null)
                return null;
            var ts = (TextSelection)ServiceCache.ExtensibilityModel.ActiveDocument.Selection;
            return (ts == null) ? null : ts.Text;
        }

        public static string GetActiveDocumentText()
        {
            var textDocument = (TextDocument)ServiceCache.ExtensibilityModel.ActiveDocument.Object("TextDocument");
            var startPoint = textDocument.StartPoint.CreateEditPoint();
            return startPoint.GetText(textDocument.EndPoint);
        }

        public static string GetStatements()
        {
            var selectionText = GetActiveDocumentSelectionText();
            return !string.IsNullOrWhiteSpace(selectionText) ? selectionText : GetActiveDocumentText();
        }
   

        public static string GetConnString()
        {
            var scriptFactory = ServiceCache.ScriptFactory;
            var connInfo = scriptFactory.CurrentlyActiveWndConnectionInfo;
            if (connInfo == null)
                return string.Empty;
            var conn = connInfo.UIConnectionInfo;
            if (conn.UserName == Dns.GetHostName() + "\\" + Environment.UserName)
                return string.Format("Server={0};Integrated Security=true;Database={1};",
                                     conn.ServerName, conn.AdvancedOptions["DATABASE"]);
            return string.Format("Server={0};uid={1};pwd={2};Database={3};",
                                 conn.ServerName, conn.UserName, conn.Password, conn.AdvancedOptions["DATABASE"]);
        }

        public static void NewScriptDocument(string text)
        {
            // create new document
            UIConnectionInfo connectionInfo = null;
            if (ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo != null)
                connectionInfo = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo;

            ServiceCache.ScriptFactory.CreateNewBlankScript(ScriptType.Sql, connectionInfo, null);

            // insert SQL definition to document
            var doc = (TextDocument)ServiceCache.ExtensibilityModel.Application.ActiveDocument.Object(null);
            doc.EndPoint.CreateEditPoint().Insert(text);
        }

    }
}
